<template>
  <div class="user-list">
    <n-card>
      <n-space vertical>
        <n-space justify="space-between">
          <n-space>
            <n-input 
              v-model:value="searchParams.username" 
              placeholder="搜索用户名" 
              clearable
              @keyup.enter="handleSearch"
            />
            <n-select
              v-model:value="searchParams.role"
              :options="roleOptions"
              placeholder="选择角色"
              clearable
              style="width: 150px;"
            />
            <n-button type="primary" @click="handleSearch">
              <template #icon><SearchOutline /></template>
              搜索
            </n-button>
          </n-space>
          <h2>用户管理</h2>
        </n-space>
        
        <n-data-table
          :columns="columns"
          :data="users"
          :loading="loading"
          :pagination="pagination"
          @update:page="handlePageChange"
        />
      </n-space>
    </n-card>
    
    <!-- 编辑用户模态框 -->
    <n-modal v-model:show="showEditModal" preset="card" title="编辑用户" style="width: 500px;">
      <n-form ref="formRef" :model="formData">
        <n-form-item label="用户名" path="username">
          <n-input v-model:value="formData.username" disabled />
        </n-form-item>
        <n-form-item label="昵称" path="nickname">
          <n-input v-model:value="formData.nickname" placeholder="请输入昵称" />
        </n-form-item>
        <n-form-item label="邮箱" path="email">
          <n-input v-model:value="formData.email" placeholder="请输入邮箱" />
        </n-form-item>
        <n-form-item label="手机号" path="phone">
          <n-input v-model:value="formData.phone" placeholder="请输入手机号" />
        </n-form-item>
        <n-form-item label="角色" path="role">
          <n-select v-model:value="formData.role" :options="roleOptions" />
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-radio-group v-model:value="formData.status">
            <n-radio :value="1">启用</n-radio>
            <n-radio :value="0">禁用</n-radio>
          </n-radio-group>
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="showEditModal = false">取消</n-button>
          <n-button type="primary" @click="handleSave">保存</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, h, onMounted } from 'vue'
import { userApi } from '@/api/user'
import { 
  NCard, NSpace, NInput, NSelect, NButton, NDataTable, NTag, NModal, 
  NForm, NFormItem, NRadioGroup, NRadio, NPopconfirm, useMessage 
} from 'naive-ui'
import { SearchOutline } from '@vicons/ionicons5'

const message = useMessage()

const loading = ref(false)
const users = ref([])
const showEditModal = ref(false)

const searchParams = ref({
  username: '',
  role: null,
  current: 1,
  size: 10
})

const pagination = ref({
  page: 1,
  pageSize: 10,
  pageCount: 1,
  itemCount: 0
})

const formData = ref({
  id: null,
  username: '',
  nickname: '',
  email: '',
  phone: '',
  role: 'USER',
  status: 1
})

const roleOptions = [
  { label: '管理员', value: 'ADMIN' },
  { label: '普通用户', value: 'USER' }
]

const columns = [
  { title: 'ID', key: 'id' },
  { title: '用户名', key: 'username' },
  { title: '昵称', key: 'nickname' },
  { title: '邮箱', key: 'email' },
  { title: '手机号', key: 'phone' },
  { 
    title: '角色', 
    key: 'role',
    render: (row) => h(NTag, { 
      type: row.role === 'ADMIN' ? 'error' : 'info' 
    }, () => row.role === 'ADMIN' ? '管理员' : '普通用户')
  },
  { 
    title: '状态', 
    key: 'status',
    render: (row) => h(NTag, { 
      type: row.status === 1 ? 'success' : 'default' 
    }, () => row.status === 1 ? '启用' : '禁用')
  },
  { 
    title: '创建时间', 
    key: 'createTime',
    render: (row) => new Date(row.createTime).toLocaleDateString('zh-CN')
  },
  {
    title: '操作',
    key: 'actions',
    render: (row) => h(NSpace, null, () => [
      h(NButton, {
        size: 'small',
        onClick: () => handleEdit(row)
      }, () => '编辑'),
      row.status === 1 
        ? h(NButton, {
            size: 'small',
            type: 'warning',
            onClick: () => handleToggleStatus(row.id, 0)
          }, () => '禁用')
        : h(NButton, {
            size: 'small',
            type: 'success',
            onClick: () => handleToggleStatus(row.id, 1)
          }, () => '启用'),
      h(NPopconfirm, {
        onPositiveClick: () => handleDelete(row.id)
      }, {
        trigger: () => h(NButton, { size: 'small', type: 'error' }, () => '删除'),
        default: () => '确定删除这个用户吗？'
      })
    ])
  }
]

const loadUsers = async () => {
  loading.value = true
  try {
    const data = await userApi.getUsers(searchParams.value)
    users.value = data.records
    pagination.value = {
      page: data.current,
      pageSize: data.size,
      pageCount: data.pages,
      itemCount: data.total
    }
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  searchParams.value.current = 1
  loadUsers()
}

const handlePageChange = (page) => {
  searchParams.value.current = page
  loadUsers()
}

const handleEdit = (user) => {
  formData.value = { ...user }
  showEditModal.value = true
}

const handleSave = async () => {
  try {
    await userApi.updateUser(formData.value.id, formData.value)
    message.success('更新成功')
    showEditModal.value = false
    loadUsers()
  } catch (error) {
    console.error(error)
  }
}

const handleToggleStatus = async (id, status) => {
  try {
    await userApi.updateStatus(id, status)
    message.success('操作成功')
    loadUsers()
  } catch (error) {
    console.error(error)
  }
}

const handleDelete = async (id) => {
  try {
    await userApi.deleteUser(id)
    message.success('删除成功')
    loadUsers()
  } catch (error) {
    console.error(error)
  }
}

onMounted(() => {
  loadUsers()
})
</script>

